import asyncio

""" 
tcp 服务端-协程异步读写
"""
Server_IP = "127.0.0.1"
Server_Port = 9966


async def tcp_echo_client(client_num: int = 256, Test_Count: int = 10):
    client_sockets = []
    for i in range(client_num):
        reader, writer = await asyncio.open_connection(Server_IP, Server_Port)
        client_sockets.append((reader, writer))
    count = 0
    while count < Test_Count:
        try:
            for i in range(client_num):
                # 1.读取输入
                # input_msg = input("请输入要发送的数据：")
                input_msg = f"client-{i} send msg: count:{count}"
                if input_msg in ("exit", "quit", "q"):
                    print("退出")
                    break

                # 2.发送
                writer.write(input_msg.encode())
                await writer.drain()

                # 3.接收
                data = await reader.read(1024)
                print(f"recv: {data.decode()}")
                # 4.检查连接是否关闭
                if not data:
                    print("socket 连接已关闭")
                    break

            count += 1
            await asyncio.sleep(1)

        except asyncio.IncompleteReadError:
            print("服务端已断开连接")
            break

    print("Close the connection")
    for i in range(client_num):
        reader, writer = client_sockets[i]
        writer.close()
        await writer.wait_closed()


async def main():
    await tcp_echo_client()


if __name__ == "__main__":
    asyncio.run(main())
